package cn.joeg.dp.singleton.register;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;


public class RegisterSingleton3 {

    private static ConcurrentMap<String, Object> register = new ConcurrentHashMap<>(0);
    private RegisterSingleton3() {}

    public static Object getInstance(String name) {
        return getInstance(name, Object.class);
    }


    @SuppressWarnings("unchecked")
    public static <T> T getInstance(String name, Class<T> classType) {
        try {
            if (register.containsKey(name)) {
                return (T) register.get(name);
            } else {
                try {
                    return (T) register.put(name, classType.newInstance());
                } catch (InstantiationException | IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        } catch (ClassCastException e) {
            e.printStackTrace();
            return null;
        }

    }

    public void sayHello() {
        System.out.println("Hello!");
    }


}
